package com.feiwo.nonego.rpc.loadbalancer.random.weight;

import com.feiwo.nonego.rpc.loadbalancer.api.ServiceLoadBalancer;
import com.feiwo.nonego.rpc.spi.annotation.SPIClass;

import java.util.List;
import java.util.Random;

/**
 *
 *
 * @author feiwo 2025-08-17
 */
@SPIClass
public class RandomWeightServiceLoadBalancer<T> implements ServiceLoadBalancer<T> {
    @Override
    public T select(List<T> servers, int hashCode, String sourceIp) {
        if (servers == null || servers.isEmpty()) {
            return null;
        }
        hashCode = Math.abs(hashCode);
        var count = hashCode % servers.size();
        if (count <= 1) {
            count = servers.size();
        }
        var random = new Random();
        var index = random.nextInt(count);
        return servers.get(index);
    }
}
